package example.oauth.http;

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import example.oauth.OAuthMessage;

public class HttpClient {
	/**
	 * 服务器发送请求
	 * @param method
	 * @param parameters
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public String execute(String url,String params) throws IOException{
		boolean isGet = true;//GET.equalsIgnoreCase(message.method);
		org.apache.http.client.HttpClient http = new DefaultHttpClient();
		String response = null;
System.out.println("请求URL："+url);
		String[] buf = params.split("&");
		for(int i=0;i<buf.length;i++){
			
			System.out.println("参数："+buf[i]);
		}
		
		if(isGet){
			HttpGet httpGet = new HttpGet(url+"?"+params);
			HttpResponse httpResponse = http.execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
	
			if(HttpStatus.SC_OK == statusCode){
				response = EntityUtils.toString(httpResponse.getEntity());
			}else{
				return String.valueOf(statusCode);
			}
			
		}
		return response;
	}
	/*
	public String execute(String url,String parames) throws Exception{
		boolean isGet = true;
		org.apache.commons.httpclient.HttpClient http = new org.apache.commons.httpclient.HttpClient();
		String response = null;
		if(isGet){
System.out.println("请求URL："+url+"?"+parames);
			GetMethod httpGet = new GetMethod(url+"?"+parames);
			int statusCode = http.executeMethod(httpGet);
			
			if(HttpStatus.SC_OK == statusCode){
				response = getData(httpGet.getResponseBodyAsStream());
			}else{
				return String.valueOf(statusCode);
			}
			
			
		}
		return response;
	}*/
	
	
	
	
	/**
	 * 从输入流获取信息
	 * @param inputStream 输入流
	 * @return
	 * @throws Exception
	 */
	/*private String getData(InputStream inputStream) throws Exception
	{
		String data = "";
		//内存缓冲区
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = -1;
		byte[] buff = new byte[1024];
		try
		{
			while((len=inputStream.read(buff))!=-1)
			{
				outputStream.write(buff, 0, len);
			}
			byte[] bytes = outputStream.toByteArray();
			data = new String(bytes);
		} catch (IOException e)
		{
			throw new Exception(e.getMessage(),e);
		}
		finally
		{
			outputStream.close();
		}
		return data;
	}*/
	
	
	
	
	
	
	
	
    static final String GET = OAuthMessage.GET;
    static final String POST = OAuthMessage.POST;
    //static final String PUT = OAuthMessage.PUT;
   //static final String DELETE = OAuthMessage.DELETE;
}
